#ifdef __cplusplus
extern "C"{
#endif
// C code...
#include "socketserver.h"
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/shm.h>

#ifdef __cplusplus
}
#endif



void on_tcp_connect(int fd, struct sockaddr_in* addr) {
    printf("New TCP connection from %s:%d (fd=%d)\n",
           inet_ntoa(addr->sin_addr), ntohs(addr->sin_port), fd);
}

void on_tcp_disconnect(int fd) {
    printf("TCP client disconnected (fd=%d)\n", fd);
}

void on_tcp_data(int fd, const unsigned char* data, int len) {
    printf("TCP data from fd=%d, len=%d: ", fd, len);
    for (int i = 0; i < len; i++) {
        printf("%02x ", data[i]);
    }
    printf("\n");
}

void on_udp_data(int fd, struct sockaddr_in* addr, const unsigned char* data, int len) {
    printf("UDP data from %s:%d(fd=%d), len=%d: ",
           inet_ntoa(addr->sin_addr), ntohs(addr->sin_port), fd, len);
    for (int i = 0; i < len; i++) {
        printf("%02x ", data[i]);
    }
    printf("\n");
}

int main(int argc, char* argv[]) {
    unsigned char buf_for_recv_udp[128];
    unsigned char buf_for_recv_tcp[128];

    socket_server_config server_config = {
        .running = 1,

        .ip = "0.0.0.0",
        .port = 8888,

        .enable_tcp = 1,
        .enable_udp = 1,

        .enable_udp_broadcast = 1,

        .enable_reuse_port    = 1,

        .bind_to_interface = NULL, // ens33

        .buf_for_recv_tcp      = buf_for_recv_tcp,
        .buf_for_recv_tcp_size = sizeof(buf_for_recv_tcp),

        .buf_for_recv_udp      = buf_for_recv_udp,
        .buf_for_recv_udp_size = sizeof(buf_for_recv_udp),

        .on_tcp_connect = on_tcp_connect,
        .on_tcp_disconnect = on_tcp_disconnect,
        .on_tcp_data = on_tcp_data,

        .on_udp_data = on_udp_data
    };

    printf("Server running on %s:%d", server_config.ip, server_config.port);
    if(server_config.enable_tcp) {
        printf("+TCP");
    }
    if(server_config.enable_udp) {
        printf("+UDP");
    }
    printf("\n");


    return socket_server_exec(&server_config);
}
